import { defineStore } from "pinia";
import type { RouteLocationNormalizedLoaded } from "vue-router";

interface Route {
  level1: string;
  level2: string;
  title: string;
}

interface User {
  account: string;
  name: string;
  nickname: string;
  avatar: string;
  phone: string;
  orgId: string;
  email: string;
  roleCodeList: string[];
  permissionCodeList: string[];
}

const useApp = defineStore("app", {
  state: () => {
    return {
      route: {
        level1: "",
        level2: "",
        title: "",
      } as Route,
      user: {
        account: "",
        name: "",
        nickname: "",
        avatar: "",
        phone: "",
        email: "",
        orgId: "",
        roleCodeList: [],
        permissionCodeList: [],
      } as User,
    };
  },
  getters: {
    routeLevel1: (state) => state.route.level1,
    routeLevel2: (state) => state.route.level2,
    routeTitle: (state) => state.route.title,
    loginUser: (state) => {
      const name = state.user.nickname || state.user.account || "";
      const roleName = state.user.name || state.user.roleCodeList[0] || "";
      const avatar = state.user.avatar || "";
      const orgId = state.user.orgId || "";
      return {
        name,
        roleName,
        avatar,
        orgId,
      };
    },
  },
  actions: {
    setRoute(data: RouteLocationNormalizedLoaded) {
      if (data.matched[1]) {
        this.route.level1 = data.matched[1].name as string;
      } else {
        this.route.level1 = "";
      }
      if (data.matched[2]) {
        this.route.level2 = data.matched[2].name as string;
      } else {
        this.route.level2 = "";
      }
      this.route.title = data?.meta?.title || (data.name as string) || "";
    },
    setUser(data: any) {
      const userInfo: any = { ...this.user };
      for (let key in userInfo) {
        if (data[key]) {
          userInfo[key] = data[key];
        }
      }
      this.user = userInfo;
    },
  },
});

export default useApp;
